<script setup>
import { ref, watch } from 'vue'
import { useScroll } from '@vueuse/core'
import SvgIcon from '../../../components/SvgIcon.vue'
import Popup from '../../../libs/Popup/Popup.vue'
import MenuMB from './components/MenuMB.vue'
import { useStore } from 'vuex'
const store = useStore()
//点击切换index
const changeIndex = (index) => {
  store.commit('category/setCurrentIndex', index)
}
// 定义 ref
const ulRef = ref(null)
const sliderRef = ref(null)
const itemRef = ref([])
const setItemRef = (el) => {
  // 这里可以根据需要处理每个 li 的 ref
  if (el) {
    itemRef.value.push(el)
  }
}
//滑块逻辑
const sliderStyle = ref({
  transform: 'translateX(4px)',
  transition: 'all 0.3s ease',
  width: '40px'
})
const { x } = useScroll(ulRef)
watch(
  () => store.getters.currentIndex,
  (newValue, oldValue) => {
    const itemBounds = itemRef.value[newValue].getBoundingClientRect()


    itemRef.value[oldValue].classList.remove('text-white')
    itemRef.value[oldValue].classList.add('text-zinc-600')

    itemRef.value[newValue].classList.remove('text-zinc-600')
    itemRef.value[newValue].classList.add('text-white')

    sliderStyle.value.width = `${itemBounds.width}px`
    sliderStyle.value.transform = `translateX(${itemBounds.left + x.value}px)`
  }
)
//下拉菜单的显示
const isVisible = ref(false)
const changeIsVisible = () => {
  isVisible.value = !isVisible.value
}
</script>
<template>
  <ul
    class="nav flex relative overflow-x-auto p-1 text-zinc-600"
    ref="ulRef"
    v-if="$store.getters.categorys"
  >
    <li
      class="shrink-0 p-1 duration-200 z-10"
      :class="{ 'text-white': index === 0 }"
      v-for="(item, index) in $store.getters.categorys"
      :key="index"
      :ref="setItemRef"
      @click="changeIndex(index)"
    >
      {{ item.name }}
    </li>
    <!-- 滑块 -->
    <li
      class="nav__slider absolute bg-slate-600 h-8 w-10 left-0 top-1/5 -translate-y-1/2 rounded-lg"
      ref="sliderRef"
      :style="sliderStyle"
    ></li>
    <!-- 汉堡按钮 -->
    <li
      class="fixed right-0 top-1/5 bg-slate-50 z-40 w-7 h-7 pr-1"
      @click="changeIsVisible"
    >
      <SvgIcon name="hamburger" class="absolute right-0 w-6 h-6" />
    </li>
  </ul>
  <Popup v-model="isVisible">
    <MenuMB @closePopup="changeIsVisible" />
  </Popup>
</template>
<style></style>
